<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>
<style>
  * {
    margin: 0;
    padding: 0;
  }

  #box {
    width: 100px;
    height: 100px;
    background: orangered;
    position: absolute;
    left: 400px;
    top: 200px;
  }
</style>

<body>
  <div id="box"></div>
  <script>
    let box = document.getElementById('box');
    // 当用户按下按键的时候，onkeydown对应的方法就会触发，咱们通过判断事件对象里的keyCode就能够知道用户到底点击的是哪个按键
    window.onkeydown = function (e) {
      console.log(e.keyCode);
      let style = getComputedStyle(box);
      // 上 38   下 40   左37  右39
      let key = e.keyCode;
      let step = 10
      switch (key) {
        case 38:
          console.log('点击的是上');
          box.style.top = parseFloat(style.top) - step + 'px';
          break;
        case 40:
          console.log('点击的是下');
          break;
        case 37:
          console.log('点击的是左');
          break;
        case 39:
          console.log('点击的是右');
          break;
      }

    }
  </script>
</body>

</html>